package com.halixun.d2app.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.multidex.MultiDex;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.halixun.d2app.WelcomeActivity;
import com.halixun.d2app.base.BasePrintInfo;
import com.halixun.d2app.bean.ClientUserInfo;
import com.halixun.d2app.bean.print.UsbPrintInfo;
import com.halixun.d2app.net.DataState;
import com.halixun.d2app.printer.USBPrinter;
import com.halixun.d2app.utils.ImageLoader;
import com.previewlibrary.ZoomMediaLoader;
import com.tencent.bugly.crashreport.CrashReport;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: MyOrderSystem
 * @Package: com.example.myordersystem.app
 * @ClassName: MyApplication
 * @Description: java类作用描述
 * @Author: hdx
 * @CreateDate: 2019/9/26 13:47
 * @UpdateUser: hdx
 * @UpdateDate: 2019/9/26 13:47
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {
    public static final String KEY_APP_IS_LOGIN = "key_app_is_login";
    public static final String KEY_CLIENT_USER_INFO = "key_client_user_info";

    public static final String KEY_DATA_PATH = "key_data_source";
    public static final String KEY_NATIVE_JSON = "key_native_json";

    private static final String TAG = MyApplication.class.getSimpleName() + "---tag";

    private static Context mContext;

    public static int startCount = 0;

    private static ActivityManage mActivityManage;

    private static String brand;

    private static boolean isSunMi = false;

    private static boolean isVertical = false;

    private static String ip;

    private static List<UsbPrintInfo> sUsbPrintInfos = new ArrayList<>();

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this.getApplicationContext();
//        NetWorkManager.getInstance().init();
        CrashReport.initCrashReport(getApplicationContext(), "462ee19ec5", false);
        registerActivityLifecycleCallbacks(this);
        ZoomMediaLoader.getInstance().init(new ImageLoader());
    }


    public static void setUsbPrint(UsbPrintInfo info){
        sUsbPrintInfos.add(info);
    }


    /**
     * 移除usb打印数据
     * @param info
     */
    public static void removeUsbPrint(UsbPrintInfo info){
        if (sUsbPrintInfos.contains(info)){
            sUsbPrintInfos.remove(info);
        }
    }


    public static List<UsbPrintInfo> getUsbPrintList(){
        return sUsbPrintInfos;
    }

    public static UsbPrintInfo getUsbPrint(UsbDevice device){
        for (UsbPrintInfo printInfo : sUsbPrintInfos){
            if (printInfo.name.equals(device.getManufacturerName())&&printInfo.id.equals(device.getDeviceName())){
                return printInfo;
            }
        }
        return null;
    }



    public static void setPrintInfoData(BasePrintInfo source , BasePrintInfo info){
        source.isPrint = info.isPrint;
        source.fractionToPrintIntervalTime = info.fractionToPrintIntervalTime;
        source.isFractionToPrint = info.isFractionToPrint;
        source.printConditions = info.printConditions;
        source.mFoodCategoryInfos = info.mFoodCategoryInfos;
    }


    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Glide.get(this).onTrimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.get(this).onLowMemory();
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (mActivityManage == null) {
            mActivityManage = new ActivityManageImpl();
        }
        mActivityManage.pushActivity(activity);
        activityDataReset(activity, savedInstanceState);
    }

    @Override
    public void onActivityStarted(Activity activity) {
        startCount++;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        startCount--;
        if (!isBackground()) {
            Glide.get(this).clearMemory();
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        activityDataSave(activity, outState);
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (mActivityManage == null) return;
        mActivityManage.popActivity(activity);
        if (mActivityManage.mActivitys.size() == 0) {
            USBPrinter.getInstance().close();
            sUsbPrintInfos.clear();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }


    protected void activityDataSave(Activity activity, Bundle outState) {
        if (outState != null) {
            outState.putBoolean(KEY_APP_IS_LOGIN, DataState.getInstance().isLoginState());
            outState.putSerializable(KEY_CLIENT_USER_INFO, DataState.getInstance().getClientUserInfo());
//            outState.putBoolean(KEY_DATA_PATH,DataState.getInstance().isGetDataFromNet());
//            outState.putString(KEY_NATIVE_JSON,DataState.getInstance().getNativeCommodityJson());
        }
    }

    protected void activityDataReset(Activity activity, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(KEY_APP_IS_LOGIN)) {
                DataState.getInstance().setLoginState(savedInstanceState.getBoolean(KEY_APP_IS_LOGIN));
            }
            if (savedInstanceState.containsKey(KEY_CLIENT_USER_INFO)) {
                DataState.getInstance().setClientUserInfo((ClientUserInfo) savedInstanceState.getSerializable(KEY_CLIENT_USER_INFO));
            }
//            if (savedInstanceState.containsKey(KEY_DATA_PATH)){
//                DataState.getInstance().setGetDataFromNet(savedInstanceState.getBoolean(KEY_DATA_PATH));
//            }
//            if (savedInstanceState.containsKey(KEY_NATIVE_JSON)){
//                DataState.getInstance().setNativeCommodityJson(DataState.getInstance().getNativeCommodityJson());
//            }
        }
    }


    /**
     * 包名判断是否为主进程
     *
     * @param
     * @return
     */
    public boolean isMainProcess() {
        return getApplicationContext().getPackageName().equals(getCurrentProcessName());
    }

    /**
     * 获取当前进程名
     */
    private String getCurrentProcessName() {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
            if (process.pid == pid) {
                processName = process.processName;
            }
        }
        return processName;
    }

    /**
     * 判断是否是k1设备
     *
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static boolean isHaveCamera() {
        HashMap<String, UsbDevice> deviceHashMap = ((UsbManager) getMyContext().getSystemService(Activity.USB_SERVICE)).getDeviceList();
        for (Map.Entry entry : deviceHashMap.entrySet()) {
            UsbDevice usbDevice = (UsbDevice) entry.getValue();
            if (!TextUtils.isEmpty(usbDevice.getInterface(0).getName()) && usbDevice.getInterface(0).getName().contains("Orb")) {
                return true;
            }
            if (!TextUtils.isEmpty(usbDevice.getInterface(0).getName()) && usbDevice.getInterface(0).getName().contains("Astra")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取ActivityManage
     *
     * @return
     */
    public static ActivityManage getmActivityManage() {
        if (mActivityManage == null) {
            mActivityManage = new ActivityManageImpl();
        }
        return mActivityManage;
    }


    /**
     * 获取当前Activity
     *
     * @return
     */
    public static Activity getCurrentActivity() {
        if (mActivityManage == null) {
            mActivityManage = new ActivityManageImpl();
            return null;
        } else {
            if (mActivityManage.mActivitys.size() == 0) {
                return null;
            } else {
                return mActivityManage.currentActivity();
            }
        }
    }

    /**
     * 获取平台信息
     *
     * @return
     */
    public static String getBrand() {
        if (TextUtils.isEmpty(brand)) {
            brand = Build.BRAND;
            isSunMi = "SUNMI".equals(brand);
        }
        return brand;
    }

    /**
     * 判断是否是商米设备
     *
     * @return
     */
    public static boolean isSunmi() {
        if (TextUtils.isEmpty(brand)) {
            brand = Build.BRAND;
            isSunMi = "SUNMI".equals(brand);
        }
        return isSunMi;
    }

    /**
     * 获取Context
     *
     * @return
     */
    public static Context getMyContext() {
        return mContext;
    }

    /**
     * 判断app是否处于后台状态
     *
     * @return
     */
    public static boolean isBackground() {
        if (startCount == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 判断是否是竖屏设备
     *
     * @return
     */
    public static boolean isVerticalScreen() {
        Activity activity = getCurrentActivity();
        if (activity != null) {
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;// 屏幕宽度
            int height = dm.heightPixels;// 屏幕宽度
            return isVertical = height > width;
        } else {
            return true;
        }
    }

    /**
     * 获取本地ip
     *
     * @return
     */
    public static String getIP() {
        if (!TextUtils.isEmpty(ip)) return ip;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                        ip = inetAddress.getHostAddress().toString();
                        return ip;
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return ip = "";
    }

}
